package logic

import (
	"context"
	"errors"
	"zhongwen/models/mysql"

	"zhongwen/zhongwenrpc/internal/svc"
	"zhongwen/zhongwenrpc/zhongwenrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectAddLogic {
	return &CollectAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectAddLogic) CollectAdd(in *zhongwenrpc.CollectAddRequest) (*zhongwenrpc.CollectAddResponse, error) {
	// todo: add your logic here and delete this line

	var novel mysql.Novel
	mysql.DB.Debug().Where("id=?", in.NovelId).Find(&novel)
	if novel.ID == 0 {
		return nil, errors.New("当前小说不存在")
	}

	var findcollect mysql.Collect
	mysql.DB.Debug().Where("id=?", in.NovelId).Where("user_id=?", in.UserId).Find(&findcollect)
	if findcollect.ID != 0 {
		return nil, errors.New("已经收藏过啦")
	}
	collect := mysql.Collect{
		UserId:  in.UserId,
		NovelId: in.NovelId,
	}
	mysql.DB.Debug().Create(&collect)
	novel.CollectNum = novel.CollectNum + 1
	mysql.DB.Debug().Updates(&novel)
	return &zhongwenrpc.CollectAddResponse{
		CollectId: int64(collect.ID),
	}, nil
}
